<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form inline>
        <el-form-item />
        <el-form-item label="">
          <el-button
            size="small"
            class="filter-item"
            type="primary"
            icon="edit"
            @click="handleCreate('create')"
            >添加</el-button
          >
          <!-- <el-button class="filter-item" style="margin-left: 10px;" @click="open(1)" type="primary" icon="edit">白名单IP</el-button>
            <el-button class="filter-item" style="margin-left: 10px;" @click="open(2)" type="primary" icon="edit">预约页面开关</el-button> -->
        </el-form-item>
      </el-form>
    </div>
    <div class="table-container">
      <el-table
        key="tableKey"
        v-loading="listLoading"
        :data="roleList"
        element-loading-text="加载中"
        border
        fit
        stripe
        highlight-current-row
        style="width: 100%"
        :header-cell-style="{
          background: '#E3ECFB',
          color: '#303133',
          fontWeight: '500'
        }"
      >
        <!-- <el-table-column align="center" label="角色编号">
          <template slot-scope="scope">
            <span>{{ scope.row.role_id }}</span>
          </template>
        </el-table-column> -->
        <el-table-column align="center" label="角色名字">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="权限描述">
          <template slot-scope="scope">
            <span>{{ scope.row.desc }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="添加时间">
          <template slot-scope="scope">
            <span>{{ scope.row.created_at }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="权限状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status == 1 ? 'success' : 'warning'">
              <span>{{ scope.row.status == 1 ? "可用" : "已禁用" }}</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="修改时间">
          <template slot-scope="scope">
            <span>{{ scope.row.updated_at }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="250px">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              style="padding-right:10px;"
              active-color="#13ce66"
              :inactive-value="2"
              :active-value="1"
              inactive-color="grey"
              @change="changeStatus(scope, scope.row.status)"
            />
            <el-button
              plain
              size="small"
              type="primary"
              @click="handleEdit(scope.row, 'edit')"
              >编辑权限
            </el-button>
            <el-button
              plain
              size="small"
              type="danger"
              @click="delRole(scope.row.role_id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form
        class="small-space"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left: 50px"
      >
        <!-- <el-form-item label="角色">
          <el-radio-group v-model="temp.role">
            <el-radio label="super">超级管理员</el-radio>
            <el-radio label="admin">普通管理员</el-radio>
          </el-radio-group>
        </el-form-item> -->

        <el-form-item label="角色名字">
          <el-input v-model="temp.name" />
        </el-form-item>

        <el-form-item label="角色描述">
          <el-input v-model="temp.desc" />
          <!-- <el-input v-if="dialogStatus == 'create'" v-model="temp.password" />
          <el-input v-else v-model="temp.password" placeholder="不填写密码则不修改密码" /> -->
        </el-form-item>
        <el-form-item label="设置权限">
          <el-tree
            ref="menu"
            :data="menus"
            :default-checked-keys="menuIds"
            :props="defaultProps"
            show-checkbox
            node-key="menu_id"
          />
        </el-form-item>
        <el-alert title="* 设置完成后需重新登录才能生效。" type="warning">
        </el-alert>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button
          v-if="dialogStatus == 'create'"
          type="primary"
          @click="create"
          >新 增</el-button
        >
        <el-button v-else type="primary" @click="update">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchRole,
  fetchRoleList,
  // fetchAdminList,
  // fetchAdmin,
  addRole,
  updateRole,
  changeRole,
  deleteRole,
  addAdmin,
  menuTree
} from "@/api/manager";

export default {
  name: "Admin",
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger"
      };
      return statusMap[status];
    }
  },
  data() {
    return {
      roleList: null,

      dialogFormVisible: false,
      temp: {},
      dialogStatus: null,
      ip: "",
      btn: "0",
      dialogTitle: "添加角色",
      menus: [],
      menuIds: [],
      defaultProps: { children: "children", label: "menu_title" }
    };
  },
  created() {
    this.getRoleList();
    this.getMenus();
    // fetchBtn().then((response) => {
    //   //console.log(response);
    //   this.ip = response.data.ip;
    //   this.btn = response.data.btn_reservation;
    // });
  },
  methods: {
    // 获取所有权限
    getMenus() {
      menuTree().then(res => {
        this.menus = res.data.menu;
        // console.log(this.menus)
      });
    },
    getRoleList() {
      this.listLoading = true;
      fetchRole().then(response => {
        this.roleList = response.data.data;
        // console.log(this.roleList)
        this.pagination = response.data;
        this.listLoading = false;
      });
    },
    // open(type) {
    //   let m
    //   if (type == 1) {
    //     m = this.ip
    //   } else {
    //     m = this.btn
    //   }
    //   this.$prompt(
    //     '请输入,多个ip请用|连接，页面开关，1表示开，0表示关',
    //     '提示',
    //     {
    //       confirmButtonText: '确定',
    //       cancelButtonText: '取消',
    //       inputValue: m
    //     }
    //   )
    //     .then(({ value }) => {
    //       editBtn({ val: value, type: type }).then((response) => {
    //         this.$message({
    //           message: response.msg,
    //           type: 'success'
    //         })
    //       })
    //     })
    //     .catch(() => { })
    // },
    handleEdit(row, status) {
      this.dialogTitle = "编辑";
      this.temp = JSON.parse(JSON.stringify(row));
      this.dialogStatus = status;
      this.dialogFormVisible = true;
      menuTree({ role_id: row.role_id }).then(res => {
        this.menus = res.data.menu;
        this.menuIds = res.data.list;
        // this.$refs.menu.setCheckedNodes(res.data.list)
      });
    },
    handleCreate(status) {
      this.dialogTitle = "添加";
      this.dialogStatus = status;
      this.dialogFormVisible = true;
      if (this.$refs.menu) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.temp = {
        role: ""
      };
    },
    create() {
      const nodeList = Array.from(
        new Set([
          ...this.$refs.menu.getCheckedKeys(),
          ...this.$refs.menu.getHalfCheckedKeys()
        ])
      );
      // console.log(nodeList, this.$refs.menu.getCheckedKeys(), 'add')
      const params = {
        ...this.temp,
        menu_ids: JSON.stringify(nodeList)
      };
      addRole(params).then(response => {
        // console.log(response);
        if (response.code == 0) {
          this.$message({
            message: response.msg,
            type: "success"
          });
          this.dialogFormVisible = false;
          this.getRoleList();
        } else {
          this.$message({
            message: response.msg,
            type: "error"
          });
        }
      });
    },
    update() {
      const nodeList = Array.from(
        new Set([
          ...this.$refs.menu.getCheckedKeys(),
          ...this.$refs.menu.getHalfCheckedKeys()
        ])
      );
      // console.log(nodeList, this.$refs.menu.getCheckedKeys(), 'add')
      const params = {
        ...this.temp,
        menu_ids: JSON.stringify(nodeList)
      };
      updateRole(params).then(response => {
        // console.log(response);
        if (response.code == 0) {
          this.$message({
            message: response.msg,
            type: "success"
          });
          this.dialogFormVisible = false;
          this.getRoleList();
        } else {
          this.$message({
            message: response.msg,
            type: "error"
          });
        }
      });
    },
    // 角色启用、禁用状态切换操作
    changeStatus(scope, status) {
      // console.log(scope.row, status);
      this.$set(this.roleList[scope.$index], "status", status == 1 ? 2 : 1);
      this.$confirm("确定要执行该操作吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          const _this = this;
          changeRole({
            role_id: scope.row.role_id,
            status: status == 1 ? 2 : 1
          }).then(response => {
            // this.confirmVisible = false;
            this.$message.success(response.msg);
            this.getRoleList();
          });
        })
        .catch(() => {
          // this.$set(this.adminList[scope.$index], 'status', status == 1 ? 2 : 1)
          // console.log(this.adminList)
          this.$message({
            type: "info",
            message: "已取消操作"
          });
        });
    },

    delRole(id) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteRole({ role_id: id }).then(response => {
            // console.log(response);
            if (response.code == 0) {
              this.$message({
                message: response.msg,
                type: "success"
              });
              this.getRoleList();
            } else {
              this.$message({
                message: response.msg,
                type: "error"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
  }
};
</script>
